package com.ruoyi.web.controller.agent;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.ResponseResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OrderStatusEnum;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.Withdraw;
import com.ruoyi.system.dto.ApiOrderReceiveAddDto;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.OrderService;
import com.ruoyi.system.vo.ApiPayResultVo;
import com.ruoyi.system.vo.SumAmountVo;
import com.ruoyi.web.controller.common.CheckTimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "商户后台:订单管理")
@RestController
@RequestMapping("agent/order")
public class AgentOrderController extends BaseController {
    @Autowired
    private OrderService orderService;
    @Resource
    private ISysConfigService configService;

    /**
     * 根据ip获取地址
     *
     * @param ip
     * @return
     */
    public static String getAddress(String ip) {

        Map map = new HashMap();
        map.put("ip", ip);
        map.put("accessKey", "alibaba-inc");
        String str = HttpUtil.post("http://ip.taobao.com/outGetIpInfo", map);

        if (!StrUtil.hasBlank(str)) {
            JSONObject jsonObject = JSONUtil.parseObj(str);
            System.out.println(jsonObject.toString());
            jsonObject = jsonObject.getJSONObject("data");
            if (jsonObject == null) {
                return null;
            }


            String province = jsonObject.getStr("province");
            String city = jsonObject.getStr("city");
            return province + " " + city;
        }
        return null;
    }


    public static void main(String[] args) {
        String ip = "8.210.119.140";
        String result = getAddress(ip);
        System.out.println(result);
        if (StrUtil.hasBlank("")) {
            System.out.println(1);
        }
    }

    private String moneyCol = "amount";

    @Log(title = "商户导出订单", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "导出订单")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Order order) {
        CheckTimeUtil.checkTime(order.getParams());
        SysUser user = this.getLoginUser().getUser();
        order.setMerchantId(user.getUserId());
        List<Order> list = orderService.list(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        util.exportExcel(response, list, "订单数据");
    }




    @ApiOperation(value = "订单列表")
    @GetMapping("list")
    public ResponseResult<List<Withdraw>> list(Order orderPay) {
        SysUser user = this.getLoginUser().getUser();
        orderPay.setMerchantId(user.getUserId());
        // orderPay.setChannelCode(domain.getChannelCode());
        Map<String, Object> map = new HashMap<>();
        this.startPage();
        List<Order> list = orderService.findList(orderPay);
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        DateTime yestodayBegin = DateUtil.offsetDay(beginOfDay, -1);

        orderPay.setOrderStatus(OrderStatusEnum.success.getValue());
        BigDecimal yestoday = orderService.sum(moneyCol, orderPay, yestodayBegin, beginOfDay);
        BigDecimal today = orderService.sum(moneyCol, orderPay, beginOfDay, new Date());
        BigDecimal totalAmount = orderService.sum(moneyCol, orderPay, null, null);

        DateTime thisMonth = DateUtil.beginOfMonth(new Date());
        DateTime dateTime = DateUtil.offsetMonth(thisMonth, -1);
        BigDecimal thisMonthAmount = orderService.sum(moneyCol, orderPay, thisMonth, new Date());
        BigDecimal preMonthAmount = orderService.sum(moneyCol, orderPay, dateTime, thisMonth);
        SumAmountVo sumAmountVo = new SumAmountVo();
        sumAmountVo.setTodayAmount(today);
        sumAmountVo.setYestodayAmount(yestoday);
        sumAmountVo.setTotalAmount(totalAmount);
        sumAmountVo.setPreMonthAmount(preMonthAmount);
        sumAmountVo.setThisMonthAmount(thisMonthAmount);
        map.put("sumAmountVo", sumAmountVo);
        map.put("pageResult", this.getPageResult(list));
        return this.setSuccessResult(map);
    }

    @ApiOperation(value = "创建订单")
    @PostMapping("createOrder")
    public ResponseResult<ApiPayResultVo> createOrder(@RequestBody ApiOrderReceiveAddDto apiChinaOrderReceiveAddDto) {
        Long userId = this.getUserId();
        apiChinaOrderReceiveAddDto.setMerchantId(userId);
        apiChinaOrderReceiveAddDto.setMerchantOrderNo(System.currentTimeMillis() + "" + userId);
        apiChinaOrderReceiveAddDto.setNotifyUrl(configService.selectConfigByKey("zfbNotifyUtl") + "/api/order/notifyMe");
        return this.setSuccessResult(orderService.apiOrder(apiChinaOrderReceiveAddDto, "sys"));
    }


}
